;
define(function(require, exports, module) {
	'use strict';
	var base = require("base");
	var constant = require("constant");
	var oData;
	var barcode = require("barcode");
	var geetest = require("geetest");
	var html_tools_dialog = require("./tools_dialog.html");
	var countdown = 60;
	var ModelDataCache = new Array();

	var E = {};

	//计算时间差-返回毫秒
	E.timeCalculator = function(startTime, endTime) {
		var msec = endTime.getTime() - startTime.getTime();
		return msec;
	};

	E.unique = function unique(arr) {
		// 遍历arr，把元素分别放入tmp数组(不存在才放)
		var tmp = new Array();
		for(var i in arr) {
			//该元素在tmp内部不存在才允许追加
			if(tmp.indexOf(arr[i]) == -1) {
				tmp.push(arr[i]);
			}
		}
		return tmp;
	}

	E.protectDoubleClick = function() {
		//		$("body").append("<div style='height: 100000px;width: 100000px; display: none; z-index: 999;background-color: transparent;position: fixed;top: 0;left: 0;' id='protectFabric'></div>");
		//		$("#protectFabric").css("display", "block");
	};

	E.cancelProtectDoubleClick = function() {
		//		$("#protectFabric").css("display", "none");
	};

	E.requireInput = function(dom) {
		var _d = $(dom).find("input,textarea,select");
		$.each(_d, function() {
			var _this = this;
			if($(_this).attr("isNULL") == 1) {
				$(_this).parent().html('<font color="#f56262">*</font>' + $(_this).parent().html());
			}
		});
	};

	//常规选项
	E.inquireCommonSelectorList = function(resonType, dom) {
		base.fnAjax({
			action: "inquireCommonSelectorList.json",
			async: false,
			nocode: true,
			oData: {
				resonType: resonType
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					//					$(dom).html("");
					$.each(data.datas, function(i, v) {
						$(dom).append('<option value=' + this.index + '>' + this.reson + '</option>');
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	//日期加减天数
	E.addDate = function(date, days) {
		var d = new Date(date);
		d.setDate(d.getDate() + days);
		var month = d.getMonth() + 1;
		var day = d.getDate();
		if(month < 10) {
			month = "0" + month;
		}
		if(day < 10) {
			day = "0" + day;
		}
		var val = d.getFullYear() + "-" + month + "-" + day;
		return val;
	};

	E.nowDate = function() {
		var date = new Date()
		var mon = date.getMonth() + 1;
		var day = date.getDate();
		var nowDay = date.getFullYear() + "-" + (mon < 10 ? "0" + mon : mon) + "-" + (day < 10 ? "0" + day : day);
		return nowDay;
	}

	//权限控制
	E.inquireCurrentOperationList = function(dom) {
		base.fnAjax({
			action: 'inquireCurrentOperationList.json',
			async: false,
			fnSuccess: function(data) {
				if(data.status == 200) {
					for(var i = 0; i < data.datas.length; i++) {
						var permission = data.datas[i];
						var permissionId = permission.permissionId;
						$.each($(dom).find(".permissionLink, input, button"), function() {
							var $this = $(this);
							if($this.attr("permissionId") == permissionId) {
								$this.removeClass("none");
							}
						});
					}
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	//权限控制
	E.existPermission = function(pid, callback1, callback2) {
		base.fnAjax({
			action: 'inquireCurrentOperationList.json',
			async: false,
			fnSuccess: function(data) {
				if(data.status == 200) {
					for(var i = 0; i < data.datas.length; i++) {
						var permission = data.datas[i];
						var permissionId = permission.permissionId;
						if(permissionId == pid) {
							callback1();
							return;
						}
						continue;
					}
					callback2();
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	E.readHTML = function(url) {
		var str = "";
		$.ajax({
			async: false,
			url: url,
			success: function(result) {
				str = result
			}
		});
		return str;
	}

	//只能输入小数
	E.clearNoNum = function() {
		$.each(arguments, function() {
			var dom = this;
			$(dom).on("keyup", function() {
				//先把非数字的都替换掉，除了数字和.
				$(dom).val($(dom).val().replace(/[^\d.]/g, ""));
				//      obj.value = obj.value.replace(/[^\d.]/g,"");
				//必须保证第一个为数字而不是.
				$(dom).val($(dom).val().replace(/^\./g, ""));
				//      obj.value = obj.value.replace(/^\./g,"");
				//保证只有出现一个.而没有多个.
				$(dom).val($(dom).val().replace(/\.{2,}/g, "."));
				//      obj.value = obj.value.replace(/\.{2,}/g,".");
				//保证.只出现一次，而不能出现两次以上
				$(dom).val($(dom).val().replace(".", "$#$").replace(/\./g, "").replace("$#$", "."));
				//      obj.value = obj.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
			});
		});
	};

	//只能输入小数-整个页面的所有输入框
	E.clearNoNumAll = function(dom) {
		$.each($(dom).find("input"), function() {
			var $this = $(this);
			if($this.attr("num") == "1") {
				E.clearNoNum($this);
			}
		});
	};

	//全选事件
	E.addCheckAllEvent = function(checkDom, checkAllDom) {
		var c = 0;
		$(checkDom).unbind("click").click(function() {
			c = 0;
			$.each($(checkDom), function() {
				if($(this).prop("checked")) {
					c++;
				}
			});
			if(c == $(checkDom).length) {
				$(checkAllDom).prop("checked", true);
			} else {
				$(checkAllDom).prop("checked", false);
			}
		});

		$(checkAllDom).unbind("click").click(function() {
			if($(checkAllDom).prop("checked")) {
				$(checkDom).prop("checked", true);
			} else {
				$(checkDom).prop("checked", false);
			}
		});
	};

	//常规选项
	E.inquireCommonSelectorListByName = function(paramName, dom) {
		base.fnAjax({
			action: "inquireSystemParamByName.json",
			async: false,
			nocode: true,
			oData: {
				paramName: paramName
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					var reasons = data.datas[0].paramValue.split(',');
					$.each(reasons, function(i, v) {
						$(dom).append('<option value=' + this + '>' + this + '</option>');
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	//文件上传
	E.uploadFile = function(fileElementId, callback) {
		if($("#" + fileElementId).val() != "") {
			$.ajaxFileUpload({
				url: "/finance/api/v1.0/uploadFile.json", //你处理上传文件的服务端
				secureuri: false,
				fileElementId: fileElementId,
				dataType: 'json',
				success: function(data) {
					callback(data);
				},
				complete: function(xml) {
					$("#" + fileElementId).change(function() {
						E.uploadFile(fileElementId, callback)
					});
				},
			});
		} else {
			base.alert(3, "请选择文件！");
		}
	};

	//文件上传
	E.fileupload = function(fileElementId, progress1, callback) {
		$(fileElementId).fileupload({
			url: "/finance/api/v1.0/uploadFile.json",
			dataType: 'json',
			progressall: function(e, data) {
				if(progress1 != null) {
					progress1(data, $(fileElementId));
				}
				var progress = parseInt(data.loaded / data.total * 100, 10);
				$('#progress .bar').css(
					'width',
					progress + '%'
				);
			},
			done: function(e, data) {
				callback(data, $(fileElementId));
			}
		});
	}

	//极验验证
	E.geetest = function(popupSubmitDom, popupCaptchaDom, success, failure) {
		$.ajax({
			// 获取id，challenge，success（是否启用failback）
			url: CONFIG.BasePath + "geetest/StartCaptchaServlet",
			type: "get",
			dataType: "JSON",
			success: function(data) {
				// 使用initGeetest接口
				// 参数1：配置参数
				// 参数2：回调，回调的第一个参数验证码对象，之后可以使用它做appendTo之类的事件
				initGeetest({
					gt: data.gt,
					challenge: data.challenge,
					product: "popup", // 产品形式，包括：float，embed，popup。注意只对PC版验证码有效
					offline: !data.success // 表示用户后台检测极验服务器是否宕机，一般不需要关注
				}, handlerPopup);
			}
		});

		//滑动验证码
		var handlerPopup = function(captchaObj) {
			$(popupSubmitDom).click(function() {
				var $this = $(this);
				var validate = captchaObj.getValidate();
				if(!validate) {
					alert('请先完成验证！');
					return;
				}
				$.ajax({
					url: CONFIG.BasePath + "geetest/VerifyLoginServlet", // 进行二次验证
					type: "post",
					dataType: "JSON",
					data: {
						// 二次验证所需的三个值
						geetest_challenge: validate.geetest_challenge,
						geetest_validate: validate.geetest_validate,
						geetest_seccode: validate.geetest_seccode
					},
					success: function(result) {
						if(result.status == "success") {
							success();
						} else {
							failure();
						}
					}
				});
			});
			// 弹出式需要绑定触发验证码弹出按钮
			captchaObj.bindOn(popupSubmitDom);
			// 将验证码加到id为captcha的元素里
			captchaObj.appendTo(popupCaptchaDom);
			// 更多接口参考：http://www.geetest.com/install/sections/idx-client-sdk.html
		};
	};

	//加载下拉框
	E.loadSelectList = function(dom, action, key, value1, value2) {
		base.fnAjax({
			action: action,
			async: false,
			oData: {
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					//					$(dom).html("");
					if(value2 == null) {
						$.each(data.datas, function(i, v) {
							$(dom).append('<option value=' + this[key] + '>' + this[value1] + '</option>');
						});
					} else {
						$.each(data.datas, function(i, v) {
							$(dom).append('<option value=' + this[key] + '>' + this[value1] + '(' + this[value2] + ')' + '</option>');
						});
					}
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	//加载货物下拉框
	E.loadBulkstockData = function(dom) {
		base.fnAjax({
			action: "inquireBulkstockInfoPageList.json",
			async: false,
			nocode: true,
			oData: {
				activeState: 1,
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					$(dom).html("");
					$.each(data.datas, function(i, v) {
						$(dom).append('<option value=' + this.bulkstockInfoId + '>' + this.bulkstockName + '(' + this.specificationName + ')' + '</option>');
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	//加载系统参数下拉框
	E.inquireSystemParamByName = function(dom, paramName) {
		base.fnAjax({
			action: "inquireSystemParamByName.json",
			async: false,
			nocode: true,
			oData: {
				paramName: paramName
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					$(dom).html("");
					$.each(data.datas[0].paramValue.split(','), function(i, v) {
						$(dom).append('<option value=' + this + '>' + this + '</option>');
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	//加载企业下拉框
	E.inquireEnterprisePageList = function(dom) {
		base.fnAjax({
			action: "inquireEnterprisePageList.json",
			async: false,
			oData: {
				state: 1,
				pageSize: 1000
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					$(dom).html("");
					$.each(data.datas, function(i, v) {
						$(dom).append('<option value=' + this.enterpriseName + ' enterpriseId=' + this.enterpriseId + '>' + this.enterpriseName + '</option>');
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	E.getCommonSelectorName = function(resonType, reasonValue) {
		var reasonName = "无";
		base.fnAjax({
			action: "inquireCommonSelectorList.json",
			async: false,
			oData: {
				resonType: resonType
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					$.each(data.datas, function(i, v) {
						if(v.index == reasonValue) {
							reasonName = v.reson;
						}
					});
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
		return reasonName;
	};

	//常规选项
	E.inquireCommonSelectorByStringList = function(resonType, dom) {
		var d = "";
		base.fnAjax({
			action: "inquireCommonSelectorList.json",
			async: false,
			nocode: true,
			oData: {
				resonType: resonType
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					$(dom).html('<option value="">请选择</option>');
					d = data.datas;
				} else {
					base.alert(2, "信息获取失败");
				}
			}
		});
		if(d.length != 0) {
			$.each(d, function(i, v) {
				$(dom).append('<option value=' + v.reson + '>' + v.reson + '</option>');
			});
		}
	};

	//加载列表
	E.loadList = function(action, dom, tplDom, o, callback, pag) {
		var pa = pag == null ? $(".pagerCon") : $(pag);
		oData = o;
		base.fnAjax({
			action: action,
			async: false,
			oData: oData, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					$(dom).html("");
					juicer.register("getValueByKey", constant.getValueByKey);
					juicer.register("changeMoneyToChinese", E.changeMoneyToChinese);
					juicer.register("formatCurrency", E.formatCurrency);
					var tpl = $(tplDom).html();
					var html = juicer(tpl, data);
					$(dom).html(html);

					if(oData != null && oData.totalPageCount != null) {
						oData.totalPageCount = data.totalPageCount;
						oData.totalRecordCount = data.totalRecordCount;

						base.pageControl(
							pa,
							oData.totalRecordCount,
							data.pageIndex,
							data.pageSize,
							function(p) {
								oData.pageIndex = p;
								E.loadList(action, dom, tplDom, o, callback, pag);
							});
					}
					callback(data);
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	//获取文件名
	E.inquireFile = function(fileUuid) {
		var fileName = "";
		if($.trim(fileUuid) != "") {
			base.fnAjax({
				action: "inquireFile.json",
				async: false,
				oData: {
					fileUuid: fileUuid
				}, //传递参数
				fnSuccess: function(data) {
					if(data.status == 200) {
						if(data.datas.length > 0) {
							fileName = data.datas[0].fileName;
						}
					} else {
						base.alert(3, data.message);
					}
				}
			});
		}
		return fileName;
	};

	//生成验证码
	E.createValidateCode = function(dom) {
		var codeLength = 4;
		var code = "";
		var selectChar = new Array('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z');
		for(var i = 0; i < codeLength; i++) {
			var charIndex = Math.floor(Math.random() * 56);
			code += selectChar[charIndex];
			if(charIndex < 10) {
				$(dom).css("background", "url(../../../res/png/vbg1.jpg)");
			} else if(charIndex < 20) {
				$(dom).css("background", "url(../../../res/png/vbg2.jpg)");
			} else if(charIndex < 30) {
				$(dom).css("background", "url(../../../res/png/vbg3.jpg)");
			} else if(charIndex < 40) {
				$(dom).css("background", "url(../../../res/png/vbg4.jpg)");
			} else {
				$(dom).css("background", "url(../../../res/png/vbg5.jpg)");
			}
		}
		if(code.length != codeLength) {
			code = "";
			E.createValidateCode();
		}
		$(dom).html(code);
		return code.toLowerCase();
	};

	E.validateCode = function() {

	}

	//自动转换数字金额为大小写中文字符,返回大小写中文字符串，最大处理到999兆
	E.changeMoneyToChinese = function(money) {
		money = money.replace(/,/g, '');
		var cnNums = new Array("零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"); //汉字的数字
		var cnIntRadice = new Array("", "拾", "佰", "仟"); //基本单位
		var cnIntUnits = new Array("", "万", "亿", "兆"); //对应整数部分扩展单位
		var cnDecUnits = new Array("角", "分", "毫", "厘"); //对应小数部分单位
		var cnInteger = "整"; //整数金额时后面跟的字符
		var cnIntLast = "元"; //整型完以后的单位
		var maxNum = 999999999999999.9999; //最大处理的数字

		var IntegerNum; //金额整数部分
		var DecimalNum; //金额小数部分
		var ChineseStr = ""; //输出的中文金额字符串
		var parts; //分离金额后用的数组，预定义

		if(money == "") {
			return "零";
		}

		money = parseFloat(money);
		if(money >= maxNum) {
			$.alert('超出最大处理数字');
			return "";
		}
		if(money == 0) {
			ChineseStr = cnNums[0] + cnIntLast + cnInteger;
			return ChineseStr;
		}
		money = money.toString(); //转换为字符串
		if(money.indexOf(".") == -1) {
			IntegerNum = money;
			DecimalNum = '';
		} else {
			parts = money.split(".");
			IntegerNum = parts[0];
			DecimalNum = parts[1].substr(0, 4);
		}
		if(parseInt(IntegerNum, 10) > 0) { //获取整型部分转换
			var zeroCount = 0;
			var IntLen = IntegerNum.length;
			for(var i = 0; i < IntLen; i++) {
				var n = IntegerNum.substr(i, 1);
				var p = IntLen - i - 1;
				var q = p / 4;
				var m = p % 4;
				if(n == "0") {
					zeroCount++;
				} else {
					if(zeroCount > 0) {
						ChineseStr += cnNums[0];
					}
					zeroCount = 0; //归零
					ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
				}
				if(m == 0 && zeroCount < 4) {
					ChineseStr += cnIntUnits[q];
				}
			}
			ChineseStr += cnIntLast;
			//整型部分处理完毕
		}
		if(DecimalNum != '') { //小数部分
			var decLen = DecimalNum.length;
			for(var i = 0; i < decLen; i++) {
				var n = DecimalNum.substr(i, 1);
				if(n != '0') {
					ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
				}
			}
		}
		if(ChineseStr == '') {
			ChineseStr += cnNums[0] + cnIntLast + cnInteger;
		} else if(DecimalNum == '') {
			ChineseStr += cnInteger;
		}
		return ChineseStr;
	};

	E.matchs = function(re, str, dialog) {
		var r = re;
		var s = $.trim(str);
		var d = dialog;
		var flag = r.test(s);
		if(flag) {} else {
			base.alert(2, dialog);
		};
	};

	E.Map = function() {
		this.container = new Object();
	}

	E.Map.prototype.put = function(key, value) {
		this.container[key] = value;
	}

	E.Map.prototype.get = function(key) {
		return this.container[key];
	}

	E.Map.prototype.keySet = function() {
		var keyset = new Array();
		var count = 0;
		for(var key in this.container) {
			// 跳过object的extend函数
			if(key == 'extend') {
				continue;
			}
			keyset[count] = key;
			count++;
		}
		return keyset;
	}

	E.Map.prototype.size = function() {
		var count = 0;
		for(var key in this.container) {
			// 跳过object的extend函数
			if(key == 'extend') {
				continue;
			}
			count++;
		}
		return count;
	}

	E.Map.prototype.remove = function(key) {
		delete this.container[key];
	}

	E.Map.prototype.toString = function() {
		var str = "";
		for(var i = 0, keys = this.keySet(), len = keys.length; i < len; i++) {
			str = str + keys[i] + "=" + this.container[keys[i]] + ";\n";
		}
		return str;
	}

	E.Map.prototype.toString = function() {
		var str = "";
		for(var i = 0, keys = this.keySet(), len = keys.length; i < len; i++) {
			if(keys[i] == 0) {
				continue;
			}
			str = str + this.container[keys[i]] + "X" + keys[i] + "<br/>";
		}
		return str;
	}

	E.showLogisticsTrajectory = function(caseNumber, waybillNumber, dom) {
		var tpl = '{@each datas as it} ' +
			'{@each it.data as item,index}  ' +
			'{@if index === 0} ' +
			'<div class="trajectoryDiv"><img src="../../../res/png/point_ing.png" />${item.workTime} ' +
			'	<br /> ' +
			'	<span>&nbsp;&nbsp;&nbsp;&nbsp;${item.details}</span> ' +
			'</div> ' +
			'{@else} ' +
			'<div class="trajectoryDiv"><img src="../../../res/png/point_ed.png" />${item.workTime} ' +
			'	<br />' +
			'	<span>&nbsp;&nbsp;&nbsp;&nbsp;${item.details}</span> ' +
			'</div> ' +
			'{@/if}  ' +
			'{@/each}  ' +
			'{@/each} ';

		base.fnAjax({
			action: "inquireFinanceContainerInventoryTrackingDetail.json",
			oData: {
				//				caseNumber:caseNumber,
				//				waybillNumber:waybillNumber
				waybillNumber: waybillNumber,
				caseNumber: caseNumber
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					var html = juicer(tpl, data);
					$(dom).html(html);
				} else {
					base.alert(3, "暂无该箱物流信息");
				}
			}
		});
	};

	E.inquireContainerInventoryLogList = function(inventoryId) {
		var tpl = '<ul>' +
			'<div class="track-rcol"><div class="track-list">' +
			'{@each datas as it,index} ' +
			'{@if index == 0}' +
			'<li class="first">' +
			' <i class="node-icon"></i>' +
			' <span class="time">${it.createDateTime} ${it.operator}</span>' +
			' <span class="txt">${it.remark}</span>' +
			'</li>' +
			'{@else}' +
			'<li class>' +
			' <i class="node-icon"></i>' +
			' <span class="time">${it.createDateTime} ${it.operator}</span>' +
			' <span class="txt">${it.remark}</span>' +
			'</li>' +
			'{@/if}' +
			'{@/each} ' +
			'</div></div>' +
			'</ul>';

		base.fnAjax({
			action: "inquireContainerInventoryLogList.json",
			oData: {
				inventoryId: inventoryId
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					layer.open({
						area: ['620px', '440px'], //宽高
						title: "货箱动态",
						type: 1,
						skin: 'layui-layer-demo', //样式类名
						closeBtn: 1, //不显示关闭按钮
						anim: 2,
						shadeClose: true, //开启遮罩开启
						content: html_tools_dialog
					});
					var html = juicer(tpl, data);
					$("#toolsDialog").html(html);
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	E.changeWarningColor = function(dom, attr) {
		$.each($(dom).find("tr"), function() {
			var time = $(this).attr(attr);
			if(time == null || time == "") {
				return;
			}
			var auditWarningMap = new E.Map();
			inquireAuditWarningPageList(auditWarningMap);

			time = time.replace(/\s|(:)|\-/g, ",");
			var timeArray = time.split(',');
			var t1 = new Date().getTime();
			var t2 = new Date(timeArray[0], timeArray[1] * 1 - 1, timeArray[2], timeArray[3], timeArray[4], timeArray[5]).getTime();
			var d = t1 - t2;
			if(parseFloat(d / 3600000) >= parseInt(auditWarningMap.get(attr).warningTime) && parseFloat(d / 3600000) < parseInt(auditWarningMap.get(attr).agingTime)) {
				$(this).css("background-color", "#fcfae0");
			} else if(parseFloat(d / 3600000) >= parseInt(auditWarningMap.get(attr).agingTime)) {
				$(this).css("background-color", "#ffeeee");
			}
		});
	}

	var inquireAuditWarningPageList = function(auditWarningMap) {
		base.fnAjax({
			action: "inquireAuditWarningPageList.json",
			async: false,
			oData: {
				pageSize: 100
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					$.each(data.datas, function() {
						var aw = {
							auditWarningId: this.auditWarningId,
							auditNode: this.auditNode,
							auditStation: this.auditStation,
							auditStationId: this.auditStationId,
							warningTime: this.warningTime,
							agingTime: this.agingTime
						}
						auditWarningMap.put(this.auditWarningId, aw);
					});
				} else {
					base.alert(3, data.message);
				}
			}
		});
	};

	//打印网页
	E.preview = function(oper) {
		if(oper < 10) {
			var bdhtml = window.document.body.innerHTML; //获取当前页的html代码
			var sprnstr = "<!--startprint" + oper + "-->"; //设置打印开始区域
			var eprnstr = "<!--endprint" + oper + "-->"; //设置打印结束区域
			var prnhtml = bdhtml.substring(bdhtml.indexOf(sprnstr) + 18); //从开始代码向后取html

			prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr)); //从结束代码向前取html
			window.document.body.innerHTML = prnhtml;
			window.print();
			window.document.body.innerHTML = bdhtml;
		} else {
			window.print();
		}
	};

	E.printit = function(printDiv, type) {
		if(type == 'preview' && !-[1, ]) {
			document.all.WebBrowser.ExecWB(7, 1);
		} else {
			$(".noprint").hide();
			var w = $(".pages").css("width");
			var w1 = $(printDiv).css("width");
			$(".pages").css("width", "297mm !important");
			$(printDiv).css("width", "297mm !important");

			window.print();
			$(".pages").css("width", w);
			$(printDiv).css("width", w1);
			$(".noprint").show();
			return false;
		}
	}

	//根据银行卡号查询银行名称
	E.getBankName = function(bankCard) {

		bankCard = bankCard.replace(/[ ]/g, "");
		var bankName = "";
		if(bankCard == null || bankCard == "") {
			return "";
		}
		$.ajaxSettings.async = false;
		$.getJSON(CONFIG.BasePath + "js/bankData/bankData.json", function(data) {
			var bankBin = 0;
			var isFind = false;
			for(var key = 10; key >= 2; key--) {
				bankBin = bankCard.substring(0, key);
				$.each(data, function(i, item) {
					if(item.bin == bankBin) {
						isFind = true;
						bankName = item.bankName.substring(0, item.bankName.indexOf('-'));
					}
				});

				if(isFind) {
					break;
				}
			}
		});
		return bankName;
	};

	//生成条形码
	E.barcode = function(dom, datas, type, settings) {
		$(dom).barcode(datas, type, settings);
	};

	E.formatCurrency = function(num) {
		if(num == '0' || num == "" || num == null) {
			return 0;
		} else if(num) {
			//将num中的$,去掉，将num变成一个纯粹的数据格式字符串
			num = num.toString().replace(/\$|\,/g, '');
			//如果num不是数字，则将num置0，并返回
			if('' == num || isNaN(num) || 0 == num) {
				return num;
			}
			//如果num是负数，则获取她的符号
			var sign = num.indexOf("-") > 0 ? '-' : '';
			if(parseFloat(num) < 0) {
				num = num.substr(1, num.length);
				sign = '-';
			}
			//如果存在小数点，则获取数字的小数部分
			var cents = num.indexOf(".") > 0 ? num.substr(num.indexOf(".")) : '';
			cents = cents.length > 1 ? cents : ''; //注意：这里如果是使用change方法不断的调用，小数是输入不了的
			//获取数字的整数数部分
			num = num.indexOf(".") > 0 ? num.substring(0, (num.indexOf("."))) : num;
			//如果没有小数点，整数部分不能以0开头
			if('' == cents) {
				if(num.length > 1 && '0' == num.substr(0, 1)) {
					return 'Not a Number ! ';
				}
			}
			//如果有小数点，且整数的部分的长度大于1，则整数部分不能以0开头
			else {
				if(num.length > 1 && '0' == num.substr(0, 1)) {
					return 'Not a Number ! ';
				}
			}
			//针对整数部分进行格式化处理，这是此方法的核心，也是稍难理解的一个地方，逆向的来思考或者采用简单的事例来实现就容易多了
			/* 也可以这样想象，现在有一串数字字符串在你面前，如果让你给他家千分位的逗号的话，你是怎么来思考和操作的?
			 *字符串长度为0/1/2/3时都不用添加
			 *字符串长度大于3的时候，从右往左数，有三位字符就加一个逗号，然后继续往前数，直到不到往前数少于三位字符为止
			 */
			for(var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++) {
				num = num.substring(0, num.length - (4 * i + 3)) + ',' + num.substring(num.length - (4 * i + 3));
			}
			//将数据（符号、整数部分、小数部分）整体组合返回
			return(sign + num + cents);
		}
	};

	//查询审批记录
	E.inquireAuditRecord = function(recordType, recordId, callback) {
		base.fnAjax({
			action: "inquireAuditRecord.json",
			async: false,
			oData: {
				recordType: recordType,
				recordId: recordId
			}, //传递参数
			fnSuccess: function(data) {
				if(data.status == 200) {
					callback(data);
				} else {
					//					base.alert(2, "信息获取失败");
				}
			}
		});
	};

	E.readFiles = function(evt, imgsDom, valueDom, id1, id2, callback) {
		var files = evt.target.files;
		//console.log(files.length);
		if(!files) {
			alert("文件不支持");
			return;
		}

		for(var i = 0; i < files.length; i++) {
			//alert(files[i]);
			var imgele = new Image();
			var thesrc = window.URL.createObjectURL(files[i]);
			imgele.src = thesrc;
			imgele.name = files[i].name;
			imgele.onload = function() {
				var canvas = document.createElement("canvas");
				canvas.setAttribute("id", id1);
				canvas.setAttribute("width", "1200px");
				canvas.setAttribute("height", "1200px");
				canvas.setAttribute("class", "none");
				canvas.setAttribute("name", this.name);
				canvas.innerHTML = "你的浏览器不支持";
				var imgs = $(imgsDom)[0];
				imgs.appendChild(canvas);
				var cxt = canvas.getContext("2d");
				cxt.drawImage(this, 0, 0, 1200, 1200);

				var canvas = document.createElement("canvas");
				canvas.setAttribute("id", id2);
				canvas.setAttribute("width", "100px");
				canvas.setAttribute("height", "100px");
				canvas.setAttribute("name", this.name);
				canvas.innerHTML = "你的浏览器不支持";
				var imgs = $(imgsDom)[0];
				imgs.appendChild(canvas);
				var cxt = canvas.getContext("2d");
				cxt.drawImage(this, 0, 0, 100, 100);

				$(canvas).unbind("click").click(function() {
					E.del(this, callback);
				});
			}
			if(i == (files.length - 1)) {
				setTimeout(function() {
					E.upload(imgsDom, valueDom, callback);
				}, 3000);
			}
		}

	};

	E.del = function(view, callback) {
		$(view).remove();
		callback();
	};

	E.upload = function(dom, valueDom, callback) {
		$.each($(dom).find("canvas.none"), function(i) {
			//alert(i);
			//			alert($(this).attr("name"));
			var canvas = this;
			//将图像输出为base64压缩的字符串  默认为image/png
			var data = canvas.toDataURL("image/jpeg");
			//alert(data);
			//删除字符串前的提示信息 "data:image/png;base64,"  
			//var b64 = data.substring(23);
			var b64 = data.split(",")[1];
			//POST到服务器上，生成图片                      
			//alert(b64);
			$.post("/finance/api/v1.0/newUploadFile.json", {
				imgData: b64,
				imgName: $(canvas).attr("name")
			}, function(reponse) {
				var data = eval('(' + reponse + ')');
				$(canvas).attr("fileUuid", data.data[0].fileUuid);
				callback(data);
			});
		});
	};
	//	
	//	点击滑动制定位置  
	//	@param scrolldom     点击的制定元素  
	//	@param scrollTime    滑动的时间  
	E.scrollto = function(scrolldom, scrollTime) {
		//查找点击dom里的属性，要在dom元素里添加  
		var sc = $(scrolldom).attr('data-scroll');
		//点击后添加的样式  
		$(scrolldom).addClass('colorF').siblings().removeClass('colorF69');
		//html。body执行动画  
		//animate() 方法执行 CSS 属性集的自定义动画。  
		$('.admin').animate({
			scrollTop: $(sc).offset().top
		}, scrollTime);

		//返回false，直接在现在位置继续执行动画  
		return false;
	};
	
	E.countDown = function(dom, text, c){
		if (c == true && countdown == 60) {
			return;
		}
		
		if (countdown == 0) { 
//	        obj.removeAttribute("disabled");    
//	        obj.value="免费获取验证码"; 
//	        countdown = 60; 
			$(dom).removeAttr("disabled");
			$(dom).val(text);
			countdown = 60;
	        return;
	    } else {
	        $(dom).attr("disabled", true); 
	        $(dom).val("重新发送(" + countdown + ")"); 
	        countdown--; 
	    } 
		setTimeout(function() {
		    E.countDown(dom, text, c)
		},1000);
	};
	
	//根据搜索模型获取缓存
	E.GetDataCache = function(whereStr) {
	    var data= $.grep(ModelDataCache, function (value) {
	       return value.whereStr == whereStr && new Date() - value.addTime < 60000;
	    });
	    if (data != null && $.trim(data) != "") {
	       return data[0].Data;
	    } else {
	       return null;
	    }
	}
	
	//根据搜索模型设置缓存
	E.SetDataCache = function(whereStr, Data) {
	    for (var i = 0; i < ModelDataCache.length; i++) {
	        if (ModelDataCache[i].whereStr == whereStr) {
	            ModelDataCache[i].Data = Data;
	　　　　　 	ModelDataCache[i].addTime = new Date();
	            return;
	        }
	    }
	    ModelDataCache.push({
	        "whereStr": whereStr,
	        "Data": Data,
	        "addTime": new Date()
	    });
	}
	
	E.stepBar = function (dom, step, datalist) {
		dom.html("");
		var timestamp = Date.parse(new Date());
		var sb = "stepBar" + timestamp;

		var str = '<div id="'+sb+'" class="ui-stepBar-wrap" style="display: block;">'+
			'<div class="ui-stepBar">'+
				'<div class="ui-stepProcess" style="width: 60%;"></div>'+
			'</div>'+
			'<div class="ui-stepInfo-wrap">'+
				'<table class="ui-stepLayout" border="0" cellpadding="0" cellspacing="0" style="width: 2073px; margin-left: -162px;">'+
				'	<tbody><tr>'+
				'	</tr>'+
				'</tbody></table>'+
			'</div>'+
		'</div>';
		
		dom.html(str);
		$.each(datalist, function() {
			var _this = this;
			var s = '<td class="ui-stepInfo" style="width: 345px;">'+
					'<a class="ui-stepSequence judge-stepSequence-pre judge-stepSequence-pre-change">'+_this.id+'</a>'+
					'<p class="ui-stepName">'+_this.name+'</p>'+
				'</td>';
			$(dom).find("table tr").append(s);
		});
		
		stepBar.init(sb, {
			step : step,
			change : true,
			animation : true
		});
	}
	
	//查询利息
	E.inquiryFinanceInterest = function(financeId, bulkstockAmount, interestDate) {
		var interest = 0;
		base.fnAjax({
			action: "inquiryFinanceInterest.json",
			nocode: true,
			async: false,
			oData: {
				financeId: financeId,
				bulkstockAmount: bulkstockAmount,
				interestDate: interestDate
			}, //传递参数
			fnSuccess: function(data) {
				if (data.status == 200) {
					interest = data.datas[0].interest;
				}else {
					base.alert(3, data.message);
				}
			}
		})
		return interest.toFixed(2);
	};
	
	//自动补全
	E.autocomplete = function(dom){
		$.widget( "custom.combobox", {
	      _create: function() {
	        this.wrapper = $( "<span>" )
	          .addClass( "custom-combobox" )
	          .insertAfter( this.element );
	 
	        this.element.hide();
	        this._createAutocomplete();
	        this._createShowAllButton();
	      },
	 
	      _createAutocomplete: function() {
	        var selected = this.element.children( ":selected" ),
	          value = selected.val() ? selected.text() : "";
	 
	        this.input = $( "<input>" )
	          .appendTo( this.wrapper )
	          .val( value )
	          .attr( "title", "" )
	          .addClass( "custom-combobox-input ui-widget ui-widget-content ui-state-default ui-corner-left" )
	          .autocomplete({
	            delay: 0,
	            minLength: 0,
	            source: $.proxy( this, "_source" )
	          })
	          .tooltip({
	            tooltipClass: "ui-state-highlight"
	          });
	 
	        this._on( this.input, {
	          autocompleteselect: function( event, ui ) {
	            ui.item.option.selected = true;
	            this._trigger( "select", event, {
	              item: ui.item.option
	            });
	          },
	 
	          autocompletechange: "_removeIfInvalid"
	        });
	      },
	 
	      _createShowAllButton: function() {
	        var input = this.input,
	          wasOpen = false;
	 
	        $( "<a>" )
	          .attr( "tabIndex", -1 )
	          .attr( "title", "显示全部" )
	          .tooltip()
	          .appendTo( this.wrapper )
	          .button({
	            icons: {
	              primary: "ui-icon-triangle-1-s"
	            },
	            text: false
	          })
	          .removeClass( "ui-corner-all" )
	          .addClass( "custom-combobox-toggle ui-corner-right" )
	          .mousedown(function() {
	            wasOpen = input.autocomplete( "widget" ).is( ":visible" );
	          })
	          .click(function() {
	            input.focus();
	 
	            // 如果已经可见则关闭
	            if ( wasOpen ) {
	              return;
	            }
	 
	            // 传递空字符串作为搜索的值，显示所有的结果
	            input.autocomplete( "search", "" );
	          });
	      },
	 
	      _source: function( request, response ) {
	        var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
	        response( this.element.children( "option" ).map(function() {
	          var text = $( this ).text();
	          if ( this.value && ( !request.term || matcher.test(text) ) )
	            return {
	              label: text,
	              value: text,
	              option: this
	            };
	        }) );
	      },
	 
	      _removeIfInvalid: function( event, ui ) {
	 
	        // 选择一项，不执行其他动作
	        if ( ui.item ) {
	          return;
	        }
	 
	        // 搜索一个匹配（不区分大小写）
	        var value = this.input.val(),
	          valueLowerCase = value.toLowerCase(),
	          valid = false;
	        this.element.children( "option" ).each(function() {
	          if ( $( this ).text().toLowerCase() === valueLowerCase ) {
	            this.selected = valid = true;
	            return false;
	          }
	        });
	 
	        // 找到一个匹配，不执行其他动作
	        if ( valid ) {
	          return;
	        }
	 
	        // 移除无效的值
	        this.input
	          .val( "" )
	          .attr( "title", "找不到 " + value)
	          .tooltip( "open" );
	        this.element.val( "" );
	        this._delay(function() {
	          this.input.tooltip( "close" ).attr( "title", "" );
	        }, 2500 );
	        this.input.data( "ui-autocomplete" ).term = "";
	      },
	 
	      _destroy: function() {
	        this.wrapper.remove();
	        this.element.show();
	      }
	    });
	    
	    $(dom).combobox();
	  };
	  
	
	/**
	* paramObj 将要转为URL参数字符串的对象
	* key URL参数字符串的前缀
	* encode true/false 是否进行URL编码,默认为true
	* js实现
	* return URL参数字符串
	*/
	E.urlEncode = function (paramObj, key, encode) {
	   if(paramObj==null) return '';
	   var paramStr = '';
	   var t = typeof (paramObj);
	   if (t == 'string' || t == 'number' || t == 'boolean') {
	     paramStr += '&' + key + '=' + ((encode==null||encode) ? encodeURIComponent(paramObj) : paramObj);
	   } else {
	     for (var i in paramObj) {
	       var k = key == null ? i : key + (paramObj instanceof Array ? '[' + i + ']' : '.' + i);
	       paramStr += E.urlEncode(paramObj[i], k, encode);
	     }
	   }
	   return paramStr;
	};
	
	 //获取url参数封装成对象
	E.GetRequest = function() {
	   var url = location.search; //获取url中"?"符后的字串
	    var theRequest = new Object();
	    if (url.indexOf("?") != -1) {
	       var str = url.substr(1);
	       var strs = str.split("&");
	       for(var i = 0; i < strs.length; i ++) {
	          theRequest[strs[i].split("=")[0]]=decodeURIComponent((strs[i].split("=")[1]));
	       }
	    }
	    return theRequest;
	 }
	   

	return E;
});